package com.yonyou.pmclouds.basecom.conf;

import com.alibaba.dubbo.config.RegistryConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import java.util.Scanner;

/**
 * 开发环境强制路由的配置
 * <p>目标是在开发环境上，如果本机启动了相应服务，则通过attachment强制路由的本机
 *
 * @author mapeif
 */
@Slf4j
@Profile("dev")
@Configuration
public class DevRouterConfiguration implements BeanPostProcessor {
    private String script;
    @Autowired
    private RegistryConfig config;

    {
        try (Scanner reader = new Scanner(this.getClass().getClassLoader().getResourceAsStream("META-INF/dubbo/dev-rule.js"))) {
            StringBuilder result = new StringBuilder();
            while (reader.hasNext()) {
                result.append(reader.nextLine());
                result.append('\n');
            }
            script = result.toString();
        }
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//        try {
//            Service service = bean.getClass().getAnnotation(Service.class);
//            if (service == null) {
//                return bean;
//            }
//            Class clz = service.interfaceClass();
//            if (clz == void.class) {
//                clz = AopUtils.getTargetClass(bean).getInterfaces()[0];
//            }
//            RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
//            Registry registry = registryFactory.getRegistry(URL.valueOf(config.getAddress()));
//            registry.register(URL.valueOf("script://10.11.88.20/" + clz.getName() + "?category=routers&dynamic=true&runtime=true&rule=" + URL.encode(script)));
//            config.getAddress();
//        } catch (Exception e) {
//            // 这个不能影响正常的启动
//            log.error(e.getMessage(), e);
//        }
//        if (bean instanceof ProjectMaintain) {
//            RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
//            Registry registry = registryFactory.getRegistry(URL.valueOf(config.getAddress()));
//            registry.register(URL.valueOf("script://0.0.0.0/com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery?category=routers&version=0.0.3&dynamic=true&runtime=true&rule=" + URL.encode(script)));
//        }
        return bean;
    }


}
